using UnityEngine;
using System.Collections;

public class RopeCam : MonoBehaviour {
	
	// array of players
	private GameObject[] players;
		
	// the additional camera offset to get screen bounds
	public float zOffset = 2;
	
	//the maximum z distance of the camera
	public float maxZDistance = 3000;

    public float singlePlayerCamDistance = 15;

    public float smoothTranslationFactor = 0.05f;

    public float smoothRotationFactor = 0.05f;
	
	// Use this for initialization
	void Start () {
	}
	
	// call this function at startup or when number of active players change
	void Refresh () {
		
		players = GameObject.FindGameObjectsWithTag("Player");
		
	}
	
	// Update is called once per frame
	void Update () {
		
		// should we
		Refresh();
		
		
		Vector3 targetPosition = new Vector3();
		
		// singleplayer cam
		if(players.Length == 1){
			
			foreach(GameObject player in players) 
			{
				targetPosition =  player.transform.position + new Vector3(0,0,Mathf.Max(- singlePlayerCamDistance, - maxZDistance));
			}
		} 
		
		// multiplayer cam
		else 
		{
			Vector3 midPoint = new Vector3();
			float greatestPlayerDistanceToMidpoint = 0;
			
			foreach(GameObject player in players)
			{
				midPoint += player.transform.position;
			}
			
			//the final midpoint between of all players
			midPoint = midPoint / players.Length;
						
			//get the greatest distance from player to midpoint
			foreach(GameObject player in players)
			{
				
				float playerDistanceToMidpoint = Vector3.Distance(player.transform.position,midPoint);
				
				if(playerDistanceToMidpoint > greatestPlayerDistanceToMidpoint)
				{
					greatestPlayerDistanceToMidpoint = playerDistanceToMidpoint;
				}
			}
			
			//calculate the depth distance of the camera
						
			float cameraDistance = (greatestPlayerDistanceToMidpoint / Mathf.Sin(30.0f * 180.0f / Mathf.PI)) * Mathf.Sin(60.0f * 180.0f / Mathf.PI);
			targetPosition = midPoint + new Vector3(0,0,Mathf.Max(cameraDistance - zOffset, - maxZDistance));
			
			//smooth lookAt
			Quaternion rotation = Quaternion.LookRotation(midPoint - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, smoothRotationFactor);

			
		}
		
		//interpolate camera towards new target position
		gameObject.transform.position = Vector3.Lerp(gameObject.transform.position, targetPosition, smoothTranslationFactor);
	}
}